package com.aruba.librouter_router

import android.app.Application
import android.content.Context
import android.content.Intent
import com.aruba.librouter_router.`interface`.IRouterGroup
import com.aruba.librouter_router.`interface`.IRouterPath
import com.aruba.librouter_router.utils.ClassUtils

/**
 * 路由中间件
 * Created by aruba on 2021/11/23.
 */
class ARouter private constructor() {

    companion object {
        val INSTANCE: ARouter by lazy { ARouter() }

        // 生成的类的package
        private val GENERATE_PACKAGE = "com.aruba.router"
    }

    /**
     * 初始化
     */
    fun init(context: Application) {
        // 获取类
        ClassUtils.getFileNameByPackageName(context, GENERATE_PACKAGE)
            .filter { className ->
                className.endsWith("group")//只获取RouterGroup
            }.forEach { className ->
                // 实例化并且调用方法
                (Class.forName(className).getConstructor().newInstance() as IRouterGroup)
                    .cacheInRouterPathByGroup(CacheMap.RouterPathByGroup)// 加入缓存中
            }
    }

    /**
     * 跳转
     */
    fun navigation(context: Context, group: String, path: String) {
        context.startActivity(createIntent(context, group, path))
    }

    /**
     * 跳转
     */
    inline fun navigation(
        context: Context,
        group: String,
        path: String,
        applyIntent: (Intent) -> Unit
    ) {
        context.startActivity(createIntent(context, group, path).apply {
            applyIntent.invoke(this)
        })
    }

    /**
     * 创建Intent
     */
    fun createIntent(context: Context, group: String, path: String): Intent {
        // 获取缓存中的RouterMeta
        CacheMap.RouterMetaByPath.getOrPut(path) {
            // 缓存中没有，就利用RouterPath生成类实例化后，调用cacheInRouterMetaByPath加入
            (CacheMap.RouterPathByGroup[group]!!.getConstructor().newInstance() as IRouterPath)
                .cacheInRouterMetaByPath(CacheMap.RouterMetaByPath)
            CacheMap.RouterMetaByPath[path]!!
        }.let { routerMeta ->
            return Intent(context, routerMeta.clazz)
        }
    }
}